<template>
	<el-dialog :title="titleMap[mode]" v-model="visible" :width="740" height="411" destroy-on-close @closed="$emit('closed')">
		<el-form :model="form" :rules="rules" :disabled="mode=='show'" ref="dialogForm" :inline="true"
				 label-width="110px"
				 label-position="left">
			<el-form-item label="药品名称" prop="medicine_name">
				<el-input v-model="form.medicine_name" placeholder="请输入药品名称" clearable></el-input>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="search">查询</el-button>
				<el-button type="success" @click="reset">重置</el-button>
			</el-form-item>
		</el-form>
		<el-main class="nopadding">
			<scTable ref="table" :apiObj="apiObj" @selection-change="selectionChange" stripe remoteSort @dataChange="tableChange"
					 remoteFilter :pageSize="params.pageSize">
				<el-table-column label="药品名称" prop="medicine_name" width="150"></el-table-column>
				<el-table-column label="规格" prop="guige" width="150"></el-table-column>
				<el-table-column label="操作" fixed="right" align="right" width="160">
					<template #default="scope">
						<el-button-group>
							<el-button text type="danger" size="small" v-if="scope.row.is_added"
										@click="addMed('cancel', scope.row, scope.$index)">取消添加
							</el-button>
							<el-button text type="primary" size="small" v-else
									   @click="addMed('add',scope.row, scope.$index)">确认添加
							</el-button>
						</el-button-group>
					</template>
				</el-table-column>
			</scTable>
		</el-main>
		<template #footer>
			<el-button @click="visible=false">取 消</el-button>
			<el-button v-if="mode!='show'" type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
		</template>
	</el-dialog>
</template>

<script>
export default {
	emits: ['success', 'closed'],
	data() {
		return {
			mode: "add",
			titleMap: {
				add: '添加药品',
			},
			visible: false,
			isSaveing: false,
			apiObj: this.$API['patient.medicine'].list,
			//表单数据
			form: {
				medicine_name: '',
			},
			selected: [],
			params: {
				pageSize: 10
			}
		}
	},
	mounted() {

	},
	methods: {
		open(mode = 'add') {
			this.mode = mode;
			this.visible = true;
			return this
		},
		reset () {
			this.form = {};
			this.$refs.table.reload(this.form)
		},
		search () {
			this.$refs.table.reload(this.form)
		},
		addMed (type, row) {
			if (type === 'add') {
				row.is_added = true;
				this.selected.push(row);
			} else {
				row.is_added = false;
				this.selected = this.selected.filter(item => item.medicine_id !== row.medicine_id);
			}
		},
		tableChange () {
			this.$refs.table.tableData.forEach(item => {
				let index = this.selected.indexOf(item.medicine_id);
				if (index !== -1) item.is_added = true;
			});
		},
		submit () {
			let selected = this.selected;
			if (selected.length == 0) {
				this.$alert('还没有选择药品', "提示", {type: 'error'})
				return;
			}
			this.visible = false;
			this.$emit('success', selected);
		}
	}
};
</script>

<style>

</style>
